package com.flowcanto.gs1demo.server;

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class GetFile extends javax.servlet.http.HttpServlet {
	Webserver server;

	// Start the thread in the constructor
	public GetFile ( Webserver server ) {
		this.server = server;
	}

	@Override
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException {
		/*
		 * At this point we must check the dir "output" for files and create a
		 * nice list of that.
		 */
		String fileName = request.getParameter("file");
		String filePath = server.applicationDirectory() + "output/" + fileName;
		
		// Move the file
		File f = new File( filePath );
		// File (or directory) to be moved
	    
		if( f.exists() ) {
			// Destination directory
			File dir = new File("output/retrieved");
	    
		    // Move file to new directory
		    boolean success = f.renameTo(new File(dir, f.getName()));
		    if (!success) {
		        System.err.println( "Wasn't able to move the file" );
		    }
		}
		
		filePath = server.applicationDirectory() + "output/retrieved/" + fileName;

		System.out.println ("sending: "+ fileName);
		response.setContentType( "text/xml;charset=utf-8" );
		java.io.PrintWriter pw = response.getWriter();
		//pw.println("test");
		try {
			BufferedReader lfile = new BufferedReader(new FileReader(filePath));
			String line;
			while ((line = lfile.readLine()) != null) {
				pw.println(line);
			}
			lfile.close();
			
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}
	
	
}
